package com.cq.hd.gateway.filter;

import com.cq.hd.gateway.utils.RequestAddParameterUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.net.URI;

@Slf4j
public class AddRequestParametersGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    public AddRequestParametersGatewayFilterFactory(){}

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return ((exchange, chain) -> {

            URI uri = exchange.getRequest().getURI();
            String host = uri.getHost();

            ServerHttpRequest newRequest = RequestAddParameterUtils.addParameter(exchange, "host", host);
            return chain.filter(exchange.mutate().request(newRequest).build());
        });
    }

}
